package com.yxsk.relay.job.admin.web.common.aop;

import com.yxsk.relay.job.admin.data.entity.BaseEntity;
import com.yxsk.relay.job.admin.web.common.utils.HttpServletUtil;
import com.yxsk.relay.job.admin.web.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.stream.Stream;

/**
 * @Author 11376
 * @CreaTime 2019/6/22 15:13
 * @Description
 */
@Slf4j
@Component
@Aspect
public class EntityOperatorHandler {

    @Pointcut("execution(* org.springframework.data.repository.CrudRepository.save*(..))")
    public void savePoint() {
    }

    @Around("savePoint()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args != null) {
            Stream.of(args).forEach(o -> {
                if (o != null && o instanceof BaseEntity) {
                    BaseEntity entity = (BaseEntity) o;
                    setOperator(entity);
                }
            });
        }
        return joinPoint.proceed(args);
    }

    private void setOperator(BaseEntity entity) {
        String operator = getOperatorFromRequest();
        entity.setCreateBy(StringUtils.hasLength(entity.getCreateBy()) ? entity.getCreateBy() : operator);
        entity.setUpdateBy(StringUtils.hasLength(operator) ? operator : entity.getUpdateBy());
    }

    private String getOperatorFromRequest() {
        // 获取token
        try {
            ServletRequestAttributes servletRequest = HttpServletUtil.getServletRequest();
            if (servletRequest != null) {
                String token = JwtUtil.getRequestToken(servletRequest.getRequest());
                if (StringUtils.hasLength(token)) {
                    return JwtUtil.getUserIdFromToken(token);
                }
            }
        } catch (Exception e) {
            // Nothing.
         //   log.error("Get user id from request error.", e);
        }
        return null;
    }

}
